package com.a3dweijing.wetouch2.network;

import android.util.Log;

import com.a3dweijing.wetouch2.BuildConfig;

import java.io.IOException;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by mokun on 2018/3/16. OKHTTP3
 */

public class OKHTTPUtil
{
    private static final byte[] LOCKER = new byte[0];
    
    private static OKHTTPUtil mInstance;
    
    public OkHttpClient mOkHttpClient;
    
    private static String TAG = "okhttp";
    
    private OKHTTPUtil()
    {
        OkHttpClient.Builder ClientBuilder = new OkHttpClient.Builder();
        if (BuildConfig.DEBUG)
        {
            ClientBuilder.readTimeout(30, TimeUnit.SECONDS);// 读取超时
            ClientBuilder.connectTimeout(10, TimeUnit.SECONDS);// 连接超时
            ClientBuilder.writeTimeout(60, TimeUnit.SECONDS);// 写入超时
            ClientBuilder.addInterceptor(new Interceptor()
            {
                @Override
                public Response intercept(Chain chain)
                    throws IOException
                {
                    Request request = chain.request();
                    Log.e(TAG, "request:" + request.toString());
                    long t1 = System.nanoTime();
                    okhttp3.Response response = chain.proceed(chain.request());
                    long t2 = System.nanoTime();
                    Log.v(TAG,
                        String.format(Locale.getDefault(),
                            "Received response for %s in %.1fms%n%s",
                            response.request().url(),
                            (t2 - t1) / 1e6d,
                            response.headers()));
                    okhttp3.MediaType mediaType = response.body().contentType();
                    String content = response.body().string();
                    Log.i(TAG, "response body:" + content);
                    return response.newBuilder().body(okhttp3.ResponseBody.create(mediaType, content)).build();
                }
            });
        }

        mOkHttpClient = ClientBuilder.build();
        
    }
    
    public static OKHTTPUtil getInstance()
    {
        if (mInstance == null)
        {
            synchronized (LOCKER)
            {
                if (mInstance == null)
                {
                    mInstance = new OKHTTPUtil();
                }
            }
        }
        return mInstance;
    }
    
    public void cancel()
    {
        mOkHttpClient.dispatcher().cancelAll();
    }
}
